package com.liuwa.sms.service.impl;


import com.liuwa.sms.exception.SmsException;
import com.liuwa.sms.service.SmsService;
import com.liuwa.sms.utils.Md5Utils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;


/**
 * @Author: Liuwa
 * @Description: 未来无线短信服务
 * @Date: 2024/3/8
 */
@Service("wlwxSmsService")
public class WlwxSmsService implements SmsService {

    private Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 对接URL
     */
    @Value("${wlwx.sms.api.url:https://sms.wlwxpro.com}")
    private String apiUrl;

    /**
     * 短信客户号
     */
    @Value("${wlwx.sms.custcode}")
    private String custCode;

    /**
     * 短信密码
     */
    @Value("${wlwx.sms.password}")
    private String password;

    /**
     * 接入号
     */
    @Value("${wlwx.sms.sp_code}")
    private String spCode;

    /**
     * 短信签名
     */
    @Value("${wlwx.sms.sign}")
    private String sign;

    /**
     * 短信签名
     */
    @Value("${wlwx.sms.template:}")
    private String template;

    public void sendCode(String phone, String code) {
        try{

            String content = "您的验证码为："+ code +"，该验证码5分钟内有效，请勿泄露于他人！";
            if(StringUtils.isNotEmpty(template)){
                content = template.replace("{code}", code);
            }
            if(StringUtils.isNotEmpty(sign)){
                content = "【"+ sign +"】" + content;
            }


            content = URLEncoder.encode(content,"utf-8");
            String sign = Md5Utils.hash(content + password);
            StringBuilder sb = new StringBuilder();
            sb.append("content=").append(content).append("&destMobiles=").append(phone)
                    .append("&sign=").append(sign).append("&cust_code=").append(custCode)
                    .append("&sp_code=").append(spCode).append("&task_id=").append(0);

            String postData = sb.toString();
            logger.info(URLDecoder.decode(postData, "UTF-8"));
            URL url = new URL(apiUrl);
            URLConnection conn = url.openConnection();
            conn.setReadTimeout(1000 * 30);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.setAllowUserInteraction(false);

            DataOutputStream server = new DataOutputStream(conn.getOutputStream());

            server.write(postData.getBytes("utf-8"));
            server.close();

            BufferedReader in = new BufferedReader(new InputStreamReader(
                    conn.getInputStream(), "utf-8"));
            String result = "", s = "";
            while ((s = in.readLine()) != null)
                result = result + s + "\r\n";
            in.close();
            logger.info("短信发送结果：{}" , URLDecoder.decode(result, "UTF-8"));
            if(!result.toUpperCase().startsWith("SUCCESS")) {
                throw new SmsException("短信发送失败");
            }

        }
        catch (SmsException ex){
            throw ex;
        }
        catch (Exception e) {

            logger.error(e.getMessage(), e);
            throw new SmsException("发送短信失败");
        }
    }



}
